package com.zhiwang.planet.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import com.bumptech.glide.Glide
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerEntertainComponent
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.event.RefreshEnergyEvent
import com.zhiwang.planet.mvp.p.EntertainPresenter
import com.zhiwang.planet.mvp.v.FictionCompleteView
import com.zhiwang.planet.util.*
import com.zhiwang.planet.widget.WebViewClientCallBack
import com.zhiwang.planet.widget.WebViewEx
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_headline_web_view.*
import org.greenrobot.eventbus.EventBus
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class HeadlineWebViewActivity : BaseActivity(), WebViewEx.OnScrollChangeListener, FictionCompleteView, View.OnTouchListener {

    val TAG = "FictionWebViewActivity"

    //初始url
    private lateinit var url: String
    //保存每次页面跳转之后的url,默认是空，防止网页加载太慢，用户回退
    private var currUrl: String = ""

    val BOOK_TAG = "news/detail"

    var shouldCount = false

    var lastX = 0f
    var lastY = 0f

    //当向后台提交时，此标记为true，暂停计时
    var pendingOrError = false

    @Inject
    lateinit var entertainPresenter: EntertainPresenter


    private val webViewClient = object : WebViewClientCallBack {

        override fun onPageFinished(view: WebView?, url: String?) {
            //打开新页面，重置标记
            pendingOrError = false
            if (url != null)
                currUrl = url
            if (view != null) {
                currUrl = view.url.toString()
            }
            toolbar.title = "头条资讯"
            val should = view?.url.toString().contains(BOOK_TAG)
            if (should) {
                restoreCount()
                timeCounterLayout.setVisible()
            } else {
                stopCount()
                timeCounterLayout.setInvisible()
            }
            shouldCount = should
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (request != null) {
                    currUrl = request.url.toString()
                }
                view?.loadUrl(request?.url.toString(), mapOf(Pair("appdevice", "android")
                        , Pair("apptoken", TokenManager.webviewHeaderToken())))
                return true
            }
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            if (url != null) {
                currUrl = url
            }
            view?.loadUrl(url, mapOf(
                    Pair("appdevice", "android"),
                    Pair("apptoken", TokenManager.webviewHeaderToken())))
            return true
        }
    }
    private val chromeClient: WebChromeClient = WebChromeClient()

    companion object {
        fun load(context: Context, url: String) {
            val intent = Intent(context, HeadlineWebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_headline_web_view)
        setSupportActionBar(toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        url = intent.getStringExtra("KEY_URL")
        initTimeCounter()
        initWebView()
        loadCurrUrl()
//        swipeRefreshLayout.setOnRefreshListener { loadCurrUrl() }
        timeCounterLayout.setOnTouchListener(this)
        masterWebView.webView?.onTouchListener = object : WebViewEx.OnTouchListener {
            override fun onTouch() {
                onScrollChange(0, 0, 0, 0)
            }

        }
        DaggerEntertainComponent.builder()
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .build()
                .inject(this)
        entertainPresenter.fictionReadingCompleteView = this
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val settings = masterWebView.webView?.settings
        settings?.javaScriptEnabled = true
        settings?.useWideViewPort = true
        settings?.domStorageEnabled = true
        settings?.blockNetworkImage = false
        settings?.blockNetworkLoads = false
        settings?.textZoom = 100
        masterWebView.webViewClientCallBack = webViewClient
        val webChromeClient: WebChromeClient = chromeClient
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        masterWebView.webView?.onScrollChangeListener = this
        masterWebView.webView?.webChromeClient = webChromeClient

//        readProgressBar.period = 30
    }

    private fun initTimeCounter() {
        //gif
        Glide.with(this)
                .load(R.drawable.yuedujindu)
                .into(gifAnimView)
        startCount()
    }

    private fun loadCurrUrl() {
        masterWebView.webView?.loadUrl(url, mapOf(
                Pair("appdevice", "android"),
                Pair("userid", TokenManager.webviewHeaderUserid()),
                Pair("apptoken", TokenManager.webviewHeaderToken())
        ))
    }

    override fun onScrollChange(l: Int, t: Int, oldl: Int, oldt: Int) {
        if (shouldCount && pendingOrError.not()) {
            readProgressBar.start()
            startCount()
        }
    }

    var yield = false

    var disposable: Disposable? = null

    var timePendingStop = 12000f

    var timePassed = 0f

    var running = false
    fun startCount() {
        timePendingStop = 12000f
        if (running.not())//避免重复 启动
            Flowable.interval(150, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .`as`(androidAutoDispose())
                    .subscribe(object : Subscriber<Long> {
                        var subscription: Subscription? = null
                        override fun onComplete() {

                        }

                        override fun onSubscribe(s: Subscription?) {
                            running = true
                            subscription = s
                            subscription?.request(1)
                        }

                        override fun onNext(t: Long?) {
                            if (timePendingStop != 0f && this@HeadlineWebViewActivity.yield.not()) {
                                timePassed += 150f
                                timePendingStop -= 150f
                                if (timePassed >= 30000)
                                    entertainPresenter.postHeadlineReadingTime(currUrl, 30)
                                else {
                                    readProgressBar.setProgress(timePassed / 30000f)
                                }
                            }
                            subscription?.request(1)
                        }

                        override fun onError(t: Throwable?) {

                        }

                    })
    }

    fun restoreCount() {
        this.yield = false
    }

    fun stopCount() {
        this.yield = true
    }

    fun dispose() {
        if (disposable != null && disposable!!.isDisposed.not()) disposable?.dispose()
    }

    override fun onFictionTimePostSuccess(s: String) {
        pendingOrError = false
        timePassed = 0f
        readProgressBar.restore()
        startCount()
        Toaster.message(s)
        EventBus.getDefault().post(RefreshEnergyEvent())
    }

    private var leftSpace = 0f
    private var topSpace = 0f
    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                lastX = event.rawX
                lastY = event.rawY
                leftSpace = lastX - timeCounterLayout.left - timeCounterLayout.translationX
                topSpace = lastY - timeCounterLayout.top - timeCounterLayout.translationY
            }

            MotionEvent.ACTION_MOVE -> {
                onProgressBarMove(
                        event.rawX - leftSpace - timeCounterLayout.left,
                        event.rawY - topSpace - timeCounterLayout.top)
            }

            MotionEvent.ACTION_UP -> {
                leftSpace = 0f
                topSpace = 0f
                animateToSide()
            }
        }
        return true
    }

    private fun animateToSide() {
        val tx = if (timeCounterLayout.centerX > masterWebView.width / 2) 0f else -timeCounterLayout.left.toFloat() + 12.dp
        timeCounterLayout.animate()
                .translationX(tx)
                .setDuration(200)
                .setInterpolator(AccelerateDecelerateInterpolator())
                .start()
    }

    private fun onProgressBarMove(deltaX: Float, deltaY: Float) {

        timeCounterLayout.translationX = Math.max(-timeCounterLayout.left.toFloat(), Math.min((masterWebView.width - timeCounterLayout.right).toFloat(), deltaX))
        timeCounterLayout.translationY = deltaY
    }

    override fun onSupportNavigateUp(): Boolean {
        onBack()
        return true
    }

    override fun onBackPressed() {
        onBack()
    }

    private fun onBack() {
        when {
            masterWebView.webView?.canGoBack() != false -> masterWebView.webView?.goBack()
            else -> suicideAfterTransition()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        dispose()
        readProgressBar.cancel()
    }
}
